package cn.itcast.dao.imp;

import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: cuisensen
 * data: 2018/6/15.
 * time: 19:14.
 */
public class UserDaoImp extends JdbcDaoSupport implements UserDao {
    //private JdbcTemplate jt=super.getJdbcTemplate();
    //这样写报空指针异常
    @Override
    public void save(User user) {
        String sql="insert into acu values(?,?,?)";
        super.getJdbcTemplate().update(sql,user.getId(),user.getName(),user.getMoney());
    }

    @Override
    public void delete(User user) {
        String sql="delete from acu where id=?";
        super.getJdbcTemplate().update(sql,user.getId());
    }

    @Override
    public void update(User user) {
        String sql="update acu set name=?,money=? where id=?";
        super.getJdbcTemplate().update(sql,user.getName(),user.getMoney(),user.getId());
    }

    @Override
    public User byId(Integer id) {
        String sql="select id,name,money from acu where id=?";
        User user=super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user=new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setMoney(resultSet.getDouble("money"));
                return user;
            }
        },id);
        return user;
    }

    @Override
    public int getTotalCount() {
        String sql="select count(*) from acu";
        Integer count=super.getJdbcTemplate().queryForObject(sql,Integer.class);
        return count;
    }

    @Override
    public List<User> getAll() {
        String sql="select id,name,money from acu";
        List<User> query = super.getJdbcTemplate().query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user=new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setMoney(resultSet.getDouble("money"));
                return user;
            }
        });
        return query;
    }
}
